package com.yanqu.road.logic.redis;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.entity.servercenter.IpInfo;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;
import java.util.Objects;

public class RedisIpToCity {

    private static Logger logger = LogManager.getLogger(RedisIpToCity.class.getName());

    /**
     * 是否有在加载
     */
    public static boolean isLoadLock(){
        return RedisManger.getRedisUtil().setnx(RedisKeyDefine.LOAD_SERVER_IP_TO_CITY_LOCK, 300);      //超时300s
    }

    /**
     * 删除加载标识
     */
    public static void deleteLoadLock(){
        RedisManger.getRedisUtil().delete(RedisKeyDefine.LOAD_SERVER_IP_TO_CITY_LOCK);      //删除
    }

    public static void setIpToCityInfo(Map<String, IpInfo> ipInfoMap){
        if(null != ipInfoMap){
            for(IpInfo ipInfo : ipInfoMap.values()){
                try{
                    RedisManger.getRedisUtil().addMapValueByKey(RedisKeyDefine.SERVER_IP_TO_CITY, ipInfo.getIp(), ipInfo);
                }catch (Exception e){
                    logger.error("setIpToCityInfo ip:{},error:{}", ipInfo.getIp(), e.getStackTrace());
                }
            }
            setHasIpToCityInfo(true);
        }
    }

    public static void clearIpToCityInfo(){
        RedisManger.getRedisUtil().delete(RedisKeyDefine.SERVER_IP_TO_CITY);
    }

    public static void setHasIpToCityInfo(boolean has){
        if(has){
            RedisManger.getRedisUtil().setString(RedisKeyDefine.HAS_SERVER_IP_TO_CITY, "1");
        }else {
            RedisManger.getRedisUtil().setString(RedisKeyDefine.HAS_SERVER_IP_TO_CITY, "0");
        }
    }

    public static boolean getHasIpToCityInfo(){
        String value = RedisManger.getRedisUtil().get(RedisKeyDefine.HAS_SERVER_IP_TO_CITY);
        return Objects.equals("1", value);
    }

    public static IpInfo getIpToCityInfo(String ip){
        IpInfo ipInfo = null;
        try{
            String value = RedisManger.getRedisUtil().getFieldFromObject(RedisKeyDefine.SERVER_IP_TO_CITY, ip);
            if(!StringUtils.isNullOrEmpty(value)){
                ipInfo = JSON.parseObject(value, IpInfo.class);
            }
        }catch (Exception e){
            logger.error("getIpToCityInfo ip:{},error:{}", ip, e.getStackTrace());
        }
        return ipInfo;
    }
}
